package com.example.wyh.intelcheckbash.bug;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompatSideChannelService;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.wyh.intelcheckbash.HttpUtil;
import com.example.wyh.intelcheckbash.LocalStorage;
import com.example.wyh.intelcheckbash.R;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.task.TaskCheckActivity;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by chen on 17/12/4.
 */

public class BugListRecordActivity extends AppCompatActivity {

    public JSONArray mTodayBugList;
    public RecyclerView mBugListView;
    public MyRecyclerAdapter mBugListAdapter;
    public LinearLayoutManager linearLayoutManager;
    public JSONArray mShowBugList = new JSONArray();
    public int totalPages = 1;
    public boolean isLoading = false;
    public int lastVisibleItem = 0;
    public static int PAGE_NUMBER = 7;
    public static int NEW_BUG_REQUEST_CODE = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bug_list_record);
        SysExitUtil.activityList.add(BugListRecordActivity.this);
        initActionBar();

        mBugListView = (RecyclerView)findViewById(R.id.bug_list_view);
        linearLayoutManager = new LinearLayoutManager(this);
        mBugListView.setLayoutManager(linearLayoutManager);
        showBugInfoInListView();
        mBugListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(final RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mBugListAdapter.getItemCount() && !isLoading) {
                    //到达底部之后如果footView的状态不是正在加载的状态,就将 他切换成正在加载的状态
                    if (mTodayBugList.length() - mShowBugList.length() > 0) {
                        isLoading = true;
                        mBugListAdapter.changeState(1);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                getData();
                            }
                        }, 2000);
                    } else {
                        mBugListAdapter.changeState(2);
                    }
                }
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //拿到最后一个出现的item的位置
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });

//        Log.e("mTodayBugList",mTodayBugList.toString());
    }

    public void jumpToBugInfo(int position)
    {
        JSONObject bugInfo = null;
        try {
            bugInfo = mShowBugList.getJSONObject(position);
            Intent intent = new Intent(BugListRecordActivity.this,BugInfoActivity.class);
            intent.putExtra("bugInfo",bugInfo.toString());
            startActivityForResult(intent, position + NEW_BUG_REQUEST_CODE + 1);
        }catch (JSONException e)
        {

        }

    }

    private void getData() {
        int endShow = mShowBugList.length() + PAGE_NUMBER;
        if (mTodayBugList.length() - mShowBugList.length() < PAGE_NUMBER)
        {
            endShow = mTodayBugList.length();
        }
        int currentShowLength = mShowBugList.length();
        for (int i = currentShowLength; i < endShow; i ++)
        {
            try {
                mShowBugList.put(mTodayBugList.getJSONObject(i));
            }catch (JSONException e)
            {

            }

        }

        isLoading = false;
        mBugListAdapter.notifyDataSetChanged();
    }
    public void showBugInfoInListView()
    {
        mTodayBugList = getBugListData();
        totalPages = mTodayBugList.length() / PAGE_NUMBER + 1;
        int number = PAGE_NUMBER;
        if (totalPages == 1)
        {
            number = mTodayBugList.length();
        }

        for (int i = 0; i < number; i ++)
        {
            try {
                mShowBugList.put(mTodayBugList.getJSONObject(i));
            }catch (JSONException e)
            {

            }
        }
        lastVisibleItem = mShowBugList.length();
        mBugListAdapter = new MyRecyclerAdapter(BugListRecordActivity.this,mShowBugList, "BugListRecordActivity");
        mBugListView.setAdapter(mBugListAdapter);
    }

    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_bug_list,new LinearLayout(BugListRecordActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }
        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("缺陷登记");
        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_bug_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BugListRecordActivity.this.finish();
            }
        });
        ImageView title_logo_id = (ImageView)findViewById(R.id.title_logo_id);
        title_logo_id.setAlpha(0.7f);

        RelativeLayout new_bug_btn = (RelativeLayout)findViewById(R.id.new_bug_btn);
        new_bug_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(BugListRecordActivity.this,BugRecordActivity.class),NEW_BUG_REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新页面
        if (requestCode == NEW_BUG_REQUEST_CODE)
        {
            refreshBugListView();
        }else {
            if (resultCode == 1002)
            {
                int position = requestCode - NEW_BUG_REQUEST_CODE - 1;
                try {
                    JSONObject updateData = new JSONObject(data.getStringExtra("uploadData"));
                    mShowBugList.getJSONObject(position).put("isUpload",updateData.getString("isUpload"));
                    mBugListAdapter.notifyDataSetChanged();
                }catch (JSONException e)
                {

                }

            }
        }
    }


    public void refreshBugListView()
    {
        mTodayBugList = getBugListData();
        mShowBugList = new JSONArray();
        totalPages = mTodayBugList.length() / PAGE_NUMBER + 1;
        int number = PAGE_NUMBER;
        if (totalPages == 1)
        {
            number = mTodayBugList.length();
        }

        for (int i = 0; i < number; i ++)
        {
            try {
                mShowBugList.put(mTodayBugList.getJSONObject(i));
            }catch (JSONException e)
            {

            }
        }
        lastVisibleItem = mShowBugList.length();
        mBugListAdapter = new MyRecyclerAdapter(BugListRecordActivity.this,mShowBugList,"BugListRecordActivity");
        mBugListView.setAdapter(mBugListAdapter);
//        mBugListAdapter.notifyDataSetChanged();
    }
    public JSONArray getBugListData()
    {
        JSONArray bug_list = new JSONArray();
        TaskDbHelper taskDbHelper = new TaskDbHelper(BugListRecordActivity.this);
        SQLiteDatabase db =  taskDbHelper.getReadableDatabase();
        String query = "user_id = '" + LocalStorage.getUserXtm(BugListRecordActivity.this)
                + "'";
        String[] columns = {"data","find_time"};
        Cursor cursor = null;
        try {
            cursor = db.query("bug_list", columns, query, null, null, null, null);
            while (cursor.moveToNext()){
                JSONObject task = new  JSONObject();
                if(cursor.getColumnIndex("data")>-1){
                    String data =  cursor.getString(cursor.getColumnIndex("data"));
                    try {
                        task =  new JSONObject(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                bug_list.put(task);
            }
        } catch (SQLException e) {
        }
        //关闭数据库
        db.close();
        //// TODO: 17/12/18 将获取的数据按照时间排序
        bug_list = sortWithFindTime(bug_list);
        return  bug_list;
    }

    public JSONArray sortWithFindTime(JSONArray allData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d1;
        Date d2;
        JSONObject temp_r = new JSONObject();
        for (int i = 0; i < allData.length() - 1; i++) {
            for (int j = i + 1; j < allData.length(); j++) {
                ParsePosition pos1 = new ParsePosition(0);
                ParsePosition pos2 = new ParsePosition(0);
                try {
                    d1 = sdf.parse(allData.getJSONObject(i).getString("fxsj"), pos1);
                    d2 = sdf.parse(allData.getJSONObject(j).getString("fxsj"), pos2);
                    if (d1.before(d2)) {//如果队前日期靠后，调换顺序
                        temp_r = allData.getJSONObject(i);
                        allData.put(i, allData.getJSONObject(j));
                        allData.put(j, temp_r);
                    }
                } catch (Exception e) {

                }

            }
        }
        return allData;
    }
}
